package com.tpu.daoclasses;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
* A layer supertype that handles the common operations for all
* Data Access Objects.
*/
public abstract class AbstractDao {
private Session session;
private Transaction tx;
public AbstractDao() {
//HibernateFactory.buildIfNeeded();
}
protected void saveOrUpdate(Object obj) {
try {
startOperation();
session.saveOrUpdate(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateFactory.close(session);
}
}
protected void delete(Object obj) {
try {
startOperation();
session.delete(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateFactory.close(session);
}
}
protected Object find(Class clazz, Long id) {
Object obj = null;
try {
startOperation();
obj = session.load(clazz, id);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateFactory.close(session);
}
return obj;
}
protected List findAll(Class clazz) {
List objects = null;
try {
startOperation();
Query query = session.createQuery(
"from " + clazz.getName());
objects = query.list();
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
HibernateFactory.close(session);
}
return objects;
}
protected void handleException(HibernateException e)
throws HibernateException {
HibernateFactory.rollback(tx);
throw new HibernateException(e);
}
protected void startOperation()
throws HibernateException {
session = HibernateFactory.openSession();
tx = session.beginTransaction();
}
}